import { ListToTree } from '@/util'
import { Menu } from 'ant-design-vue'
import { Menu as IMenu } from './src/types'
import { computed, defineComponent, PropType, Ref, ref, watchEffect } from 'vue'
import { useRoute } from 'vue-router'
import { renderMenu } from './src/Menu'
import { useMenus } from './src/useMenus'

export default defineComponent({
  props: {
    menus: {
      type: Array as PropType<IMenu[]>,
      default: [],
    },
    mode: {
      type: String as PropType<string>,
      default: 'inline',
    },
  },
  setup(props) {
    const { menus } = props

    const route = useRoute()
    const { getParents } = useMenus()

    const defaultSelect = ref([`${menus[0].id}`])
    const defaultOpenSelect: Ref<string[]> = ref([])

    watchEffect(() => {
      if (route.name != undefined) {
        const menu = menus.find((m) => m.route == route.name)

        if (menu) {
          defaultSelect.value = [`${menu.id}`]
          defaultOpenSelect.value = props.mode == 'inline' ? getParents(menu.id, menus) : []
        }
      }
    })

    const items = computed(() => {
      let items: IMenu[] = []
      ListToTree(menus, items)
      return items
    })

    return () => (
      <Menu
        {...props}
        v-models={[
          [defaultSelect.value, 'selectedKeys'],
          [defaultOpenSelect.value, 'openKeys'],
        ]}
      >
        {items.value.map((v) => renderMenu(v))}
      </Menu>
    )
  },
})
